package com.cc.rabbittestdemo.Task;

import com.ruoyi.cc.mapper.MerchantMapper;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 队列删除Job：Quartz定时任务的核心逻辑
 */
@Component
public class DeleteQueueJob implements Job {

    /**
     * 注入RabbitAdmin：用于删除队列
     */
    @Resource
    private AmqpAdmin amqpAdmin;

    /**
     * 注入RedisTemplate：用于清理队列状态记录
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 定时任务执行逻辑：延迟lastTime后执行
     * @param context 任务执行上下文（包含队列名称等参数）
     * @throws JobExecutionException 任务执行异常
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 1. 从JobDataMap中获取队列名称（创建队列时传入的参数）
        JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
        String queueName = jobDataMap.getString("queueName");

        try {
            // 2. 验证Redis中是否存在该队列记录（避免重复删除）
            Boolean hasKey = redisTemplate.hasKey("queue:" + queueName);
            if (Boolean.TRUE.equals(hasKey))
                {
                // 3. 删除RabbitMQ队列（包含队列的绑定关系和消息）
                amqpAdmin.deleteQueue(queueName, false, false);
                System.out.println("队列[" + queueName + "]已删除（延迟时间：" + jobDataMap.getInt("lastTime") + "秒）");

                // 4. 清理Redis中的队列记录
                redisTemplate.delete("queue:" + queueName);
                // 5. 执行目标方法：更新优惠券状态
                merchantMapper.updateCouponStatus(queueName);
                }
            } catch (Exception e)
            {
            throw new JobExecutionException("删除队列[" + queueName + "]失败", e);
            }

    }
}